package com.banksystem.Util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.banksystem.Jwt.JwtKit;
import com.banksystem.entity.userinfo;

@Component
public class TokenUtil {

	@Autowired
	private RedisUtil redis;
	/*
	 * 从请求解析出当前用户
	 */
	public Object getUser(HttpServletRequest request){
		String token = getCookie(request);
		if(!StringUtils.isEmpty(token)){
			String username = JwtKit.getJwtUser(token);
			if(StringUtils.isEmpty(username)){
				return null;
			}
			userinfo user = (userinfo) redis.get(username);
			return user;			
		}
		return null;
	}
	
	/*
	 * 从请求中获取token
	 */
	public String getCookie(HttpServletRequest request){
		String authHeader = request.getHeader(JwtKit.header);
		if(StringUtils.isEmpty(authHeader)||"null".equals(authHeader)){
			Cookie[] cookies = request.getCookies();
			for (Cookie c : cookies) {
				String name = c.getName();
				if(name.equals(JwtKit.header)){
					authHeader = c.getValue();
					break;
				}
			}
		}
		if(!StringUtils.isEmpty(authHeader)){
			String tokenPrefix = authHeader.substring(0, JwtKit.tokenPrefix.length());
			if(tokenPrefix.equals(JwtKit.tokenPrefix)){
				authHeader = authHeader.substring(tokenPrefix.length(), authHeader.length());
			}
		}
		return authHeader;
	}
	
	public Object findUseridBytoken(HttpServletRequest request){
		userinfo user = (userinfo) getUser(request);
		return user.getUid();
	}
	
	public String findUsernameBytoken(HttpServletRequest request){
		userinfo user = (userinfo) getUser(request);
		return user.getUsername();
	}
}
